package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${spring.servlet.multipart.location}")
    private String location;

    /**
     * 菜品管理图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());
        //已经获取到file对象,需要对file对象进行拷贝操作.将file对象上传到指定路径下
        //1.获取file的全路径,然后将后缀取出待用
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String endName = originalFilename.substring(index);//.jpg
        //通过UUID的方式获取新的文件名
        String fileName = UUID.randomUUID() + endName;
        //通过配置文件Value注入的方式,获取接收上传文件的路径地址

        //2.获取file文件的资源,采用transferTo方法将文件进行转存
        File dir = new File(location);
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(location + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name,HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
//            FileInputStream fileInputStream = new FileInputStream(new File(location + name));
//            ServletOutputStream outputStream = response.getOutputStream();
            //response.setContentType("image/jpeg");
            //使用FileCopyUtils拷贝文件
            byte[] bytes = FileCopyUtils.copyToByteArray(new File(location + name));
            ServletOutputStream outputStream = response.getOutputStream();

            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
